<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
            v-model="queryParams.productName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="积分区间">
        <el-input
          v-model="queryParams.exchangePointsMin"
          placeholder="最小积分"
          style="width: 100px;"
          clearable
          @keyup.enter="handleQuery"
        />
        <span style="margin: 0 8px;">~</span>
        <el-input
          v-model="queryParams.exchangePointsMax"
          placeholder="最大积分"
          style="width: 100px;"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input
            v-model="queryParams.status"
            placeholder="请输入状态"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="SKU" prop="productSn">
        <el-input
            v-model="queryParams.productSn"
            placeholder="请输入SKU编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="goAddProduct"
        >添加积分商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['promotion:products:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['promotion:products:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['promotion:products:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="市场价" align="center" prop="originalPrice" />
      <el-table-column label="结算价" align="center" prop="price" />
      <el-table-column label="库存数量" align="center" prop="stockQuantity" />
      <el-table-column label="活动剩余库存" align="center" prop="activityRemainingStock" />
      <el-table-column label="兑换积分" align="center" prop="exchangePoints" />
      <el-table-column label="所属店铺" align="center" prop="storeName" />
      <el-table-column label="活动时间" align="center" width="240">
        <template #default="scope">
          <span>
            {{ parseTime(scope.row.activityStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }} ~
            {{ parseTime(scope.row.activityEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === '已开始'"
            link
            type="primary"
            @click="handleClose(scope.row)"
          >关闭</el-button>
          <el-button
            v-else-if="scope.row.status === '已关闭'"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['promotion:products:edit']"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改积分商品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="活动剩余库存" prop="activityRemainingStock">
          <el-input v-model="form.activityRemainingStock" placeholder="请输入活动剩余库存" />
        </el-form-item>
        <el-form-item label="兑换积分" prop="exchangePoints">
          <el-input v-model="form.exchangePoints" placeholder="请输入兑换积分" />
        </el-form-item>
        <el-form-item label="活动开始时间" prop="activityStartTime">
          <el-date-picker clearable
            v-model="form.activityStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="activityEndTime">
          <el-date-picker clearable
            v-model="form.activityEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择活动结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Products">
import { listProducts, getProducts, delProducts, addProducts, updateProducts } from "@/api/promotion/products"
import { useRouter, useRoute } from 'vue-router'
import { onMounted, watch } from 'vue'

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

function goAddProduct() {
  router.push('/promotion/products/add')
}

const productsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: null,
    exchangePoints: null,
    exchangePointsMin: null,
    exchangePointsMax: null,
    status: null
  },
  rules: {
    productId: [
      { required: true, message: "关联商品表ID不能为空", trigger: "blur" }
    ],
    shopId: [
      { required: true, message: "关联店铺表ID不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "关联积分商品分类表ID不能为空", trigger: "change" }
    ],
    stockQuantity: [
      { required: true, message: "库存数量不能为空", trigger: "blur" }
    ],
    activityRemainingStock: [
      { required: true, message: "活动剩余库存不能为空", trigger: "blur" }
    ],
    exchangePoints: [
      { required: true, message: "兑换积分不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询积分商品列表 */
function getList() {
  loading.value = true
  listProducts(queryParams.value).then(response => {
    productsList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error => {
    console.error('获取积分商品列表失败：', error)
    loading.value = false
    proxy.$modal.msgError("获取积分商品列表失败：" + error.message)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    productId: null,
    shopId: null,
    categoryId: null,
    stockQuantity: null,
    activityRemainingStock: null,
    exchangePoints: null,
    activityStartTime: null,
    activityEndTime: null,
    status: null,
    exchangePointsMin: null,
    exchangePointsMax: null
  }
  proxy.resetForm("productsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加积分商品"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value
  getProducts(_id).then(response => {
    // 跳转到修改页面，并传递商品数据
    router.push({
      path: '/promotion/products/update',
      query: { 
        id: _id,
        productData: JSON.stringify(response.data)
      }
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProducts(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProducts(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除积分商品编号为"' + _ids + '"的数据项？').then(function() {
    return delProducts(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('promotion/products/export', {
    ...queryParams.value
  }, `products_${new Date().getTime()}.xlsx`)
}

/** 关闭按钮操作 */
function handleClose(row) {
  proxy.$modal.confirm('是否确认关闭该活动？').then(function() {
    // 更新状态为已关闭
    const updateData = {
      id: row.id,
      status: '已关闭'
    }
    return updateProducts(updateData)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("已关闭")
  }).catch(() => {})
}

// 监听路由变化，检测是否需要刷新
watch(() => route.query.refresh, (newVal) => {
  if (newVal) {
    getList()
    // 清除refresh参数
    router.replace({ query: {} })
  }
})

// 页面加载时检查是否需要刷新
onMounted(() => {
  if (route.query.refresh) {
    getList()
    // 清除refresh参数
    router.replace({ query: {} })
  }
})

getList()
</script>
